package com.lehecai.ucenter.action.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lehecai.ucenter.action.BaseAction;
import com.lehecai.ucenter.bean.TreeViewBean;
import com.lehecai.ucenter.bean.UserSessionBean;
import com.lehecai.ucenter.constant.GlobalConstant;
import com.lehecai.ucenter.entity.permission.Permission;
import com.lehecai.ucenter.entity.permission.Role;
import com.lehecai.ucenter.service.permission.PermissionService;
import com.lehecai.ucenter.service.permission.RoleService;

public class RoleAction extends BaseAction {
	private static final long serialVersionUID = 2436161530465382824L;
	private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

	private RoleService roleService;
	private PermissionService permissionService;
	private Role role;

	private String func;// 用于区分输入的操作

	private List<Long> permissions;

	private List<Role> roles;

	public String handle() {
		logger.info("进入查询角色");
		roles = roleService.getAll();
		return "list";
	}

	public String manage() {
		logger.info("进入更新角色信息");
		if (role != null) {
			if (role.getName() == null || "".equals(role.getName())) {
				logger.error("角色名称为空");
				super.setErrorMessage("角色名称不能为空");
				return "failure";
			}
			
			// 一次性读出所有权限
            List<Permission> allPermissionList = permissionService.getAll();
            Map<Long, Permission> permissionMap = new HashMap<Long, Permission>();
            // 转置map
            if (allPermissionList != null) {
                for (Permission permission : allPermissionList) {
                	permissionMap.put(permission.getId(), permission);
                }
            }
			List<Permission> perms = new ArrayList<Permission>();
			if(permissions != null){
				for(Long permId : permissions){
					perms.add(permissionMap.get(permId));
				}
			}
			roleService.manage(role, perms);
			//修改的是自己的权限就更新session，如果修改的为其他角色则不更新
			UserSessionBean userSessionBean = (UserSessionBean)super.getSession().get(GlobalConstant.USER_SESSION_KEY);
			if (userSessionBean != null && role.getId() != null && userSessionBean.getRole().getId().longValue() == role.getId().longValue()) {
				userSessionBean.setRole(role);
				List<Permission> havePermissionList = roleService.findPermissionsByRole(role);
				userSessionBean.setPermissions(havePermissionList);
			}
		} else {
			logger.error("添加角色错误，提交表单为空");
			super.setErrorMessage("添加角色错误，提交表单不能为空");
			return "failure";
		}
		super.setForwardUrl("/user/role.do");
		logger.info("更新角色信息结束");
		return "success";
	}

	/**
	 * 转向添加/修改角色
	 */
	public String input() {
		logger.info("进入输入角色信息");
		if (role != null) {
			if (role.getId() != null) {
				if ("copy".equals(func)) {// 复制
					role.setValid(true);// 设置有效
					role.setRestriction(true);// 设置限制IP
				} else {// 修改
					role = roleService.get(role.getId());
				}
			}
		} else {
			role = new Role();
			role.setRestriction(false);
			role.setValid(true);
		}
		return "inputForm";
	}

	public String view() {
		logger.info("进入查看角色详情");
		if (role != null && role.getId() != null) {
			role = roleService.get(role.getId());
		} else {
			logger.error("查看角色详情，编码为空");
			super.setErrorMessage("查看角色详情，编码不能为空");
			return "failure";
		}
		logger.info("查看角色详情结束");
		return "view";
	}

	public String del() {
/*		logger.info("进入删除角色");
		if (role != null && role.getId() != null) {
			role = roleService.get(role.getId());
			if(role != null && role.getUsers() != null && (!role.getUsers().isEmpty())){
				logger.error("删除角色，已有用户使用");
				super.setErrorMessage("删除角色，已有用户使用");
				return "failure";
			}
			roleService.delete(role);
		} else {
			logger.error("删除角色， 编码为空");
			super.setErrorMessage("删除角色，编码不能为空");
			return "failure";
		}
		super.setForwardUrl("/user/role.do");
		logger.info("删除角色结束");*/
		return "forward";
	}

	public void findPermissions() {
		logger.info("进入查询权限");
		HttpServletResponse response = ServletActionContext.getResponse();
		if (role != null && role.getId() != null) {
			List<Permission> permissions = permissionService.getAll();
			role = roleService.get(role.getId());
			List<Permission> ownPermissions = roleService.findPermissionsByRole(role);
			List<TreeViewBean> list = new ArrayList<TreeViewBean>();
			for (Permission permission : permissions) {
				TreeViewBean treeViewBean = new TreeViewBean();
				treeViewBean.setId(permission.getId().toString());
				treeViewBean.setParentId(permission.getParentId().toString());
				boolean own = false;
				if(ownPermissions != null){
					for(Permission ownPermission :  ownPermissions){
						if(permission.getId() == ownPermission.getId()){
							own = true;
							break;
						}
					}
				}
				if(!own){
					treeViewBean.setText("<input type='checkbox' name='permissions' value='"+ permission.getId().toString()+ "' class='perms'>&nbsp;"+ permission.getName());
				}else{
					treeViewBean.setText("<input type='checkbox' name='permissions' value='"+ permission.getId().toString()+ "' checked='checked' class='perms'>&nbsp;"+ permission.getName());
				}
				treeViewBean.setClasses("");
				list.add(treeViewBean);
			}
			List<TreeViewBean> nodeList = new ArrayList<TreeViewBean>();
			for(TreeViewBean node1 : list){
				boolean mark = false;
				for(TreeViewBean node2 : list){
					if(!node1.getParentId().equals("0") && node1.getParentId().equals(node2.getId())){
						mark = true;
						if(node2.getChildren() == null)
							node2.setChildren(new ArrayList<TreeViewBean>());
						node2.getChildren().add(node1); 
						break;
					}
				}
				if(!mark){
					nodeList.add(node1); 
				}
			}
			JSONArray ja = JSONArray.fromObject(nodeList);
			System.out.println(ja.toString());
			PrintWriter out = null;
			response.setContentType("text/json; charset=utf-8");
			try {
				out = response.getWriter();
				out.println(ja.toString());
				out.flush();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public List<Role> getRoles() {
		return roles;
	}

	public void setRoles(List<Role> roles) {
		this.roles = roles;
	}

	public PermissionService getPermissionService() {
		return permissionService;
	}

	public void setPermissionService(PermissionService permissionService) {
		this.permissionService = permissionService;
	}

	public String getFunc() {
		return func;
	}

	public void setFunc(String func) {
		this.func = func;
	}

	public List<Long> getPermissions() {
		return permissions;
	}

	public void setPermissions(List<Long> permissions) {
		this.permissions = permissions;
	}
}
